package util;

public class SnowflakeIdGenerator {

    // 开始时间戳 2021-01-01 00:00:00
    private final static long START_TIMESTAMP = 1609430400000L;

    // 数据中心ID所占位数
    private final static long DATA_CENTER_ID_BITS = 2L;
    // 设备ID所占位数
    private final static long DEVICE_ID_BITS = 2L;
    // 序列号所占位数
    private final static long SEQUENCE_BITS = 64 - START_TIMESTAMP - DATA_CENTER_ID_BITS - DEVICE_ID_BITS;

    // 最大值
    private final static long MAX_DATA_CENTER_ID = -1L ^ (-1L << DATA_CENTER_ID_BITS);
    private final static long MAX_DEVICE_ID = -1L ^ (-1L << DEVICE_ID_BITS);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BITS);

    // 移位偏移量
    private final static long DEVICE_ID_SHIFT = SEQUENCE_BITS;
    private final static long DATA_CENTER_ID_SHIFT = DEVICE_ID_BITS + DEVICE_ID_SHIFT;
    private final static long TIMESTAMP_LEFT_SHIFT = DATA_CENTER_ID_BITS + DATA_CENTER_ID_SHIFT;

    private long dataCenterId;
    private long deviceId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(long dataCenterId, long deviceId) {
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("Data center ID cannot be greater than " + MAX_DATA_CENTER_ID + " or less than 0");
        }
        if (deviceId > MAX_DEVICE_ID || deviceId < 0) {
            throw new IllegalArgumentException("Device ID cannot be greater than " + MAX_DEVICE_ID + " or less than 0");
        }
        this.dataCenterId = dataCenterId;
        this.deviceId = deviceId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID.");
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;

            if (sequence == 0L) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) |
                (dataCenterId << DATA_CENTER_ID_SHIFT) |
                (deviceId << DEVICE_ID_SHIFT) |
                sequence;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }
    public static String ID(int n){
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        long id = idGenerator.nextId();
        String strId = String.valueOf(id);
        strId = strId.substring(strId.length() - n); // 获取后n位数字作为ID
        return strId;
    }
}

